package com.yue.yadmin.service.imp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yue.yadmin.mapper.SysRoleMenuMapper;
import com.yue.yadmin.mapper.SysUserMapper;
import com.yue.yadmin.model.SysMenu;
import com.yue.yadmin.model.SysRoleMenu;
import com.yue.yadmin.model.SysUser;
import com.yue.yadmin.service.SysUserSerivce;
import com.yue.yadmin.utils.PropertiesUtils;
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserSerivce{

	@Autowired
	SysUserMapper sysUserMapper;
	@Autowired
	SysRoleMenuMapper sysRoleMenuMapper;
	
	@Override
	public List<String> findRoles(long userId) {
		return sysUserMapper.findRoles(userId);
	}

	@Override
	public List<String> findPermissions(long userId) {
		return sysUserMapper.findPermissions(userId);
	}
	
	@Override
	@Transactional
	public void updateAdminRolePerm(List<SysMenu> permissionMenus){
		if(permissionMenus==null)return;
		//获取配置的admin角色id
		String adminRoleIdStr = PropertiesUtils.get("adminRoleId");
		if(StringUtils.isBlank(adminRoleIdStr))return;
		Long adminRoleId = Long.parseLong(adminRoleIdStr);
		SysRoleMenu sysRoleMenu = new SysRoleMenu();
		sysRoleMenu.setRoleId(adminRoleId);
		List<SysRoleMenu> adminRoleMenus = sysRoleMenuMapper.select(sysRoleMenu);
		Map<Long,Long> adminRoleIdMap = new HashMap<Long, Long>(); 
		for(int i=0,total=adminRoleMenus.size();i<total;i++){
			sysRoleMenu = adminRoleMenus.get(i);
			adminRoleIdMap.put(sysRoleMenu.getMenuId(), sysRoleMenu.getId());
		}
		//根据菜单权限新增
		for(int i=0,total=permissionMenus.size();i<total;i++){
			SysMenu sysMenu = permissionMenus.get(i);
			Long roleMenuId = adminRoleIdMap.remove(sysMenu.getId());
			if(roleMenuId==null){
				sysRoleMenu = new SysRoleMenu();
				sysRoleMenu.setMenuId(sysMenu.getId());
				sysRoleMenu.setRoleId(adminRoleId);
				sysRoleMenu.setCreaterId(adminRoleId);
				sysRoleMenuMapper.insertSelective(sysRoleMenu);
			}
		}
		//将多余的菜单权限删除
		for(Long key:adminRoleIdMap.keySet()) sysRoleMenuMapper.deleteByPrimaryKey(adminRoleIdMap.get(key));
	}

}
